﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Config
{
	using CxExtension;
	public class BaseConfig
	{
		public string id { get; set; }
		public string name { get; set; }
		public virtual string Key { get { return id; } }
		public void Parse(Dictionary<string,string> map)
		{
			OnParse(map);
			OnParseAfter();
		}
		public virtual void OnParseAfter()
		{

		}
		public static bool operator true(BaseConfig self)
		{
			return self != null;
		}
		public static bool operator false(BaseConfig self)
		{
			return self == null;
		}
		public virtual void OnParse(Dictionary<string,string> map)
		{
			this.SetValue(map);
			var key = this.Key;
			if(string.IsNullOrEmpty(key))
			{
				Debug.LogErrorFormat("[{0}]类配置id不能为null",GetType().Name);
				return;
			}
			//dataMap[key] = this;
		}
	}
	public class BaseConfig<T>:BaseConfig where T : BaseConfig
	{
		private static Dictionary<string,BaseConfig> _dataMap;// = new Dictionary<string,BaseConfig>();
		public static Dictionary<string,BaseConfig> dataMap
		{
			get
			{
				if(_dataMap == null)
				{
					_dataMap = new Dictionary<string,BaseConfig>();
				}
				return _dataMap;
			}
		}
		public static void ClearMap()
		{
			dataMap.Clear();
		}
		public static BaseConfig GetBase(string id)
		{
			BaseConfig t = null;
			if(!dataMap.TryGetValue(id,out t))
			{
				if(id != "0")
				{
					Debug.LogWarningFormat("id = {0} 不存在{1}",id,typeof(T).Name);
				}
			}
			return t;
		}
		public static T Get(string id)
		{
			var v = GetBase(id);
			return v as T;
		}
		public override void OnParse(Dictionary<string,string> map)
		{
			base.OnParse(map);
			var key = Key;
			if(dataMap.ContainsKey(key))
			{
				Debug.LogWarningFormat("配置表{0}中发现重复key:{1},已经被新的value覆盖",GetType().Name,key);
			}
			dataMap[key] = this;
		}
	}
}
